package com.atguigu.schedule.controller;

import com.atguigu.schedule.common.Result;
import com.atguigu.schedule.pojo.SysSchedule;
import com.atguigu.schedule.service.SysScheduleService;
import com.atguigu.schedule.service.impl.SysScheduleServiceImpl;
import com.atguigu.schedule.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 增加日程的请求 /schedule/add
 * 查询日程的请求 /schedule/find
 * 修改日程的请求 /schedule/update
 * 删除日程的请求 /schedule/remove
 *
 * @author yuezi2048
 * @version 1.0
 */
@WebServlet("/schedule/*")
public class SysScheduleController extends BaseController {
    private SysScheduleService scheduleService = new SysScheduleServiceImpl();

    protected void removeSchedule(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int sid = Integer.parseInt(req.getParameter("sid"));
        // 调用service方法， 删除数据
        scheduleService.removeSchedule(sid);

        // 响应数据，因为响应回去不管成没成功，都会刷新页面，由用户判定即可
        WebUtil.writeJson(resp, Result.ok(null));
    }

    protected void updateSchedule(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收请求体的JSON串，转换成SysSchedule对象
        SysSchedule schedule = WebUtil.readJson(req, SysSchedule.class);
        // 更新到数据库
        scheduleService.updateSchedule(schedule);

        // 更新完后响应成功
        WebUtil.writeJson(resp, Result.ok(null));
    }

    protected void addDefaultSchedule(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收请求中的uid参数
        int uid = Integer.parseInt(req.getParameter("uid"));

        // 调用服务层方法，向数据库增加一条空记录
        scheduleService.addDefault(uid);

        // 响应结果
        WebUtil.writeJson(resp, Result.ok(null));
    }

    protected void findAllSchedule(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收请求中的uid参数
        int uid = Integer.parseInt(req.getParameter("uid"));

        // 查询用户的所有日程
        List<SysSchedule> itemList = scheduleService.findItemListByUid(uid);

        // 将用户的所有日程放入res对象(为了以后拓展，习惯是发出去map)
        Map<String, Object> data = new HashMap<>();
        data.put("itemList", itemList);
        Result<Map<String, Object>> result = Result.ok(data);

        // res对象转换为JSON响应给客户端
        WebUtil.writeJson(resp, result);

    }
}
